package cn.taobaoke.restful.config;

import cn.taobaoke.restful.interceptor.AccessInterceptor;
import cn.taobaoke.restful.interceptor.ApiLoginInterceptor;
import cn.taobaoke.restful.interceptor.TbkExceptionHandler;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * WebAppConfiguration
 *
 * @author : yangzuo
 * @since : 2017/3/12
 */
@Configuration
@ComponentScan("cn.taobaoke.restful.interceptor")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebAppConfiguration implements WebMvcConfigurer {

    private final @NonNull AccessInterceptor accessInterceptor;

    private final @NonNull ApiLoginInterceptor apiLoginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(accessInterceptor).addPathPatterns("/**");
        registry.addInterceptor(apiLoginInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/accounts/login")
                .excludePathPatterns("/api/products/**")
                .excludePathPatterns("/api/robots/**")
                .excludePathPatterns("/api/third/**")
                .excludePathPatterns("/api/files/excel");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE");
    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new TbkExceptionHandler());
    }
}
